<template>
  <view class="itinerary-editor">
    <!-- 导航栏 -->
    <AdaptiveNavBar :showBack="true" :showHome="false" :showShadow="false" text-color="#333333" background-color="#ffffff" title="具体行程安排" />

    <!-- 内容区域 -->
    <view class="content-wrapper" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
      <!-- 行程天数列表 -->
      <view class="days-container">
        <view class="add-day-section">
          <view class="add-day-btn" style="position: relative;border-bottom: 1rpx solid #eee;" @tap="addDayBefore">
			<view class="day-title">
			  {{ days.length }} 日 行程
			</view>
            <view style="display: flex;" v-if="!shouldShowAddDayTop && days.length > 0">
				<text class="btn-plus">+</text>
				<text class="btn-text">添加上一日行程</text>
			</view>
          </view>
        </view>
        
        <view v-for="(day, dayIndex) in days" :key="dayIndex" class="day-card">
          <!-- 日期标题和展开/收起按钮 -->
          <view class="day-header" @click="toggleDayExpand(dayIndex)">
              <view class="day-tag-container">
                <view class="day-badge">D{{ dayIndex + 1 }}</view>
                <view class="day-item-title">{{ day.main || `` }}</view>
              </view>
            <view class="expand-icon">
              <image 
                src="/static/systemIcon/arrow-bottom.png" 
                class="arrow-icon"
                :class="{ 'arrow-expanded': day.expanded }"
              />
            </view>
          </view>

          <!-- 行程详情 -->
          <view v-if="day.expanded" class="day-details">
            <!-- 行程项目 -->
            <view v-for="(item, itemIndex) in day.items" :key="itemIndex" class="itinerary-detail-item">
              <view class="item-time-container">
                <view class="item-time-container-left">
					<text class="item-time">{{ item.startTime }}</text>
					<text class="item-type">{{ item.title }}</text>
					<text class="item-separator">|</text>
					<text class="item-name">{{ item.alt }}</text>
				</view>
                <view class="action-btn edit-btn" v-if="!isApplyCall || !item.isOriginal" @click="editItineraryItem(dayIndex, itemIndex)">编辑</view>
              </view>
              
              <view class="item-details">
                <view class="item-detail-row">
                  <view class="detail-label">
					  <FontIcon name="icon-time" class="detail-label-icon"></FontIcon>
				  </view>
                  <text class="detail-value">{{ item.startTime }} - {{ item.endTime }}</text>
                </view>
                <view class="item-detail-row">
                  <view class="detail-label">
                  	<FontIcon name="icon-location" class="detail-label-icon"></FontIcon>
                  </view>
                  <view class="detail-value address-display">
                    <text v-if="getAddressName(item.address)" class="address-name">{{ getAddressName(item.address) }}</text>
                    <text v-if="getAddressLocation(item.address)" class="address-location">{{ getAddressLocation(item.address) }}</text>
                  </view>
                </view>
                <view class="item-detail-row" v-if="item.description">
					<view class="detail-label">
						<FontIcon name="icon-intro" class="detail-label-icon"></FontIcon>
					</view>
                  <text class="detail-value">{{ item.description }}</text>
                </view>
              </view>
              
              <view class="item-actions">
                
              </view>
            </view>
            
            <!-- 添加项目按钮 -->
            <view class="add-item-section">
              <view class="add-item-btn" @tap="showAddItemModal(dayIndex)">
                <text class="btn-plus">+</text>
                <text class="btn-text">添加具体行程安排</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 添加天数按钮 - 独立于day-card标签外 -->
        <view class="add-day-section" style="border-top:1rpx solid #eeeeee" :style="days.length > 0?'':'margin-top:20rpx'">
          <view class="add-day-btn" @tap="addDay">
            <text class="btn-plus">+</text>
            <text class="btn-text">添加一日行程</text>
          </view>
        </view>
      </view>

    </view>


    <!-- 添加/编辑项目弹窗 -->
    <up-modal :show="showModal" :showConfirmButton="false" :title="isEditMode ? '编辑行程项目' : '添加行程项目'">
      <view class="modal-content">
        <!-- 天数选择器 - 显示当前选择的天数，不可修改 -->
        <view class="form-group">
          <text class="form-label">天/DAY</text>
          <view class="day-selector">
            第{{ currentDayIndex + 1 }}天
          </view>
        </view>

        <!-- 行程与服务安排 - 五个标签选择 -->
        <view v-for="type in ['集散', '交通', '餐饮', '活动', '住宿']" :key="type" class="itinerary-type-card" :class="{ selected: selectedItemType === type }" @tap="selectItemType(type)">
          <view class="type-card-header">
            <text class="type-title">行程与服务安排</text>
            <text class="type-name" :class="{ active: selectedItemType === type }">{{ type }}</text>
            <up-icon name="arrow-right" size="20" color="#999"></up-icon>
          </view>
          
          <!-- 类型描述 -->
          <view class="type-description">
            {{ getTypeDescription(type) }}
          </view>
          
          <!-- 时间范围 -->
          <view class="time-range-container">
            <text class="time-label">{{ getTimeLabel(type) }}</text>
            <view class="time-pickers">
              <up-button class="time-picker-btn" @tap.stop="showTimePicker('start')" type="text" size="default" :plain="true">
                {{ tempItem.startTime || (type === '餐饮' ? '12:00' : '14:00') }}
              </up-button>
              <text class="time-separator">-</text>
              <up-button class="time-picker-btn" @tap.stop="showTimePicker('end')" type="text" size="default" :plain="true">
                {{ tempItem.endTime || (type === '餐饮' ? '13:00' : '17:00') }}
              </up-button>
            </view>
          </view>
          
          <!-- 地址位置 -->
          <view class="address-container">
            <text class="address-label">地址位置</text>
            <up-button class="address-select-btn" @tap.stop="selectAddress" type="text" size="default" :plain="true">
              {{ tempItem.address || getAddressPlaceholder(type) }}
              <up-icon name="location" size="16" color="#007aff"></up-icon>
            </up-button>
          </view>
          
          <!-- 详细说明 -->
          <view class="description-container">
            <up-textarea class="form-textarea" v-model="tempItem.description" :placeholder="getDescriptionPlaceholder(type)" placeholderStyle="color: #999" />
          </view>
          
          <!-- 服务详情按钮 -->
          <view class="service-detail-container">
            <up-button class="service-detail-btn" type="text" size="default">
              项目导入服务指南行程计划 详情
              <up-icon name="arrow-right" size="16" color="#999"></up-icon>
            </up-button>
          </view>
        </view>

        <view class="modal-actions">
          <up-button class="cancel-btn" @tap="closeModal" type="default" size="default" :plain="true">
            取消
          </up-button>
          <up-button class="confirm-btn" @tap="confirmModalAction" type="primary" size="default" color="#0081ff">
            {{ isEditMode ? '保存修改' : '确认添加' }}
          </up-button>
        </view>
      </view>
    </up-modal>

    <!-- 时间选择器 -->
    <view class="time-picker-container" v-show="isShowTimePicker">
      <up-datetime-picker :show="isShowTimePicker" v-model="timePickerValue" hasInput mode="time"
        :title="timePickerType === 'start' ? '选择开始时间' : '选择结束时间'" @confirm="confirmTimePicker"
        @cancel="cancelTimePicker"></up-datetime-picker>
    </view>
  </view>
</template>

<script>
import { useProductStore } from '../../store/product';

export default {
  data() {
    return {
      GM_STATUS_BAR_HEIGHT: uni.getSystemInfoSync().statusBarHeight,
      days: [],
      productStore: null,
      // 公司信息
      companyInfo: null,
      // 业务类型判断
      isDestinationReception: false, // 目的地接待业务
      isGroupBusiness: false, // 组团业务
      // 申请调用模式
      isApplyCall: false,
      // 模态框相关
      showModal: false,
      isEditMode: false,
      currentDayIndex: 0,
      currentItemIndex: -1,
      selectedItemType: '',
      tempItem: {
        title: '',
        alt: '',
        address: '',
        startTime: '',
        endTime: '',
        description: ''
      },
      // 时间选择器相关
      isShowTimePicker: false,
      timePickerValue: '',
      timePickerType: 'start'
    };
  },

  computed: {
    // 判断是否有至少一个行程项目
    hasAtLeastOneItem() {
      return this.days.some(day => day.items && day.items.length > 0);
    },
	// 顶部按钮是否显示
	shouldShowAddDayTop(){

		// 公司信息条件：companyInfo.businessType为2
		const isBusinessType2 = this.companyInfo && this.companyInfo.businessType === 2;
		
		// 业务类型条件：目的地接待业务或组团业务
		const isTargetBusiness = this.isDestinationReception || this.isGroupBusiness;
		
		return isBusinessType2 && isTargetBusiness;
	},
  },

  mounted() {
    // 初始化productStore
    this.productStore = useProductStore();
    // 检查是否为申请调用模式
    this.checkApplyCallMode();
    // 加载初始数据
    this.loadInitialData();
    // 获取公司信息和判断业务类型
    this.loadCompanyInfo();
    this.checkBusinessType();
  },
  
  onShow() {
    // 页面显示时刷新数据
    if (this.productStore) {
      this.loadInitialData();
    }
  },

  methods: {
    // 检查是否为申请调用模式
    checkApplyCallMode() {
      try {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const options = currentPage.options || {};
        this.isApplyCall = options.isApplyCall === 'true';
      } catch (error) {
        console.error('检查申请调用模式失败:', error);
      }
    },
    // 获取公司信息
    loadCompanyInfo() {
      try {
        const companyInfo = uni.getStorageSync('companyInfo');
        if (companyInfo) {
          this.companyInfo = companyInfo;
        }
      } catch (error) {
        console.error('获取公司信息失败:', error);
      }
    },
    
    // 判断业务类型
    checkBusinessType() {
      try {
        // 获取页面参数或路由信息来判断业务类型
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const options = currentPage.options || {};
        
        // 根据页面参数或路由路径判断业务类型
        // 这里需要根据实际的路由规则来判断
        const route = currentPage.route || '';
        
        // 判断是否为目的地接待业务
        this.isDestinationReception = route.includes('destination') || 
                                     route.includes('reception') ||
                                     options.businessType === 'destination';
        
        // 判断是否为组团业务
        this.isGroupBusiness = route.includes('group') || 
                              route.includes('team') ||
                              options.businessType === 'group';
        
        // 也可以通过其他方式判断，比如从全局状态或缓存中获取
        const businessType = uni.getStorageSync('currentBusinessType');
        if (businessType) {
          this.isDestinationReception = businessType === 'destination';
          this.isGroupBusiness = businessType === 'group';
        }
      } catch (error) {
        console.error('判断业务类型失败:', error);
      }
    },
    
    // 获取描述标签
    getDescriptionLabel(type) {
      const labels = {
        '集散': '集散说明',
        '交通': '交通说明',
        '餐饮': '用餐说明',
        '活动': '活动描述',
        '住宿': '住宿说明',
        '用餐': '用餐说明'
      };
      return labels[type] || '详细描述';
    },
    
    // 根据行程类型返回对应的描述标签
    getItemTypeText(item) {
      // 根据行程类型返回对应的文本
      const typeMap = {
        '集散': '集散',
        '交通': '交通',
        '餐饮': '用餐',
        '活动': '活动',
        '住宿': '住宿'
      };
      return typeMap[item.title] || item.title || '活动';
    },
    
    // 编辑行程项目
    editItineraryItem(dayIndex, itemIndex) {
      // 跳转到行程详情编辑页面
      uni.navigateTo({
        url: `/public/create/itinerarySon?dayIndex=${dayIndex}&itemIndex=${itemIndex}`
      });
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    
    // 删除行程项目
    deleteItem(dayIndex, itemIndex) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除此行程项目吗？',
        success: (res) => {
          if (res.confirm) {
            this.days[dayIndex].items.splice(itemIndex, 1);
            
            // 检查删除后该天是否还有行程项目
            const remainingItems = this.days[dayIndex].items;
            if (!remainingItems || remainingItems.length === 0) {
              // 如果该天没有行程项目了，删除这一天
              this.days.splice(dayIndex, 1);
              
              // 重新计算所有天数的day属性
              this.days.forEach((day, index) => {
                day.day = index + 1;
              });
              
              console.log('该天已无行程项目，已删除该天');
            }
            
            // 更新store数据
            if (this.productStore && this.productStore.subPageData && this.productStore.subPageData.specificItinerary) {
              this.productStore.subPageData.specificItinerary = [...this.days];
            }
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      });
    },
    // 加载初始数据
    loadInitialData() {
      try {
        // 首先尝试从store获取数据
        if (this.productStore && this.productStore.subPageData && this.productStore.subPageData.specificItinerary) {
          const storeData = this.productStore.subPageData.specificItinerary;
          if (storeData && storeData.length > 0) {
            // 如果是申请调用模式，标记原有数据为 isOriginal: true
            this.days = storeData.map(day => ({
              ...day,
              expanded: true, // 默认展开所有天
              items: day.items ? day.items.map(item => ({
                ...item,
                // 申请调用模式下：如果 isOriginal 未定义或为 true，则标记为 true（原有数据）；如果为 false，则保持 false（新增数据）
                isOriginal: this.isApplyCall ? (item.isOriginal === false ? false : true) : false
              })) : []
            }));
            
            // 对每个天数的行程项目按时间排序
            this.sortAllDayItems();
            return;
          }
        }
        this.days = [];
      } catch (error) {
        console.error('加载行程数据失败:', error);
        // 默认为空
        this.days = [];
      }
    },

    // 切换天数展开状态
    toggleDayExpand(dayIndex) {
      try {
        // 切换当前天数的展开状态
        this.days[dayIndex].expanded = !this.days[dayIndex].expanded;
      } catch (error) {
        console.error('切换天数展开状态失败:', error);
      }
    },

    // 将时间字符串转换为分钟数
    timeToMinutes(timeStr) {
      if (!timeStr) return 0;
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    },

    // 对所有天数的行程项目按时间排序
    sortAllDayItems() {
      this.days.forEach(day => {
        if (day.items && day.items.length > 0) {
          day.items.sort((a, b) => {
            const timeA = this.timeToMinutes(a.startTime || '00:00');
            const timeB = this.timeToMinutes(b.startTime || '00:00');
            return timeA - timeB;
          });
        }
      });
      console.log('所有天数的行程项目已按时间排序');
    },

    // 获取项目类型对应的标签
    getItemTypeLabel(type) {
      const typeLabels = {
        '集散': '集散 | ',
        '活动': '活动 | ',
        '交通': '交通 | ',
        '餐饮': '用餐 | ',
        '住宿': '住宿 | '
      };
      return typeLabels[type] || '';
    },

    // 显示添加项目弹窗
    showAddItemModal(dayIndex) {
      // this.currentDayIndex = dayIndex;
      // this.isEditMode = false;
      // this.selectedItemType = '';
      // this.tempItem = {
      //   title: '',
      //   alt: '',
      //   address: '',
      //   startTime: '',
      //   endTime: '',
      //   description: ''
      // };
      // this.showModal = true;
      uni.navigateTo({
        url: `/public/create/itinerarySon?dayIndex=${dayIndex}`
      })
    },

    // 显示编辑项目弹窗
    showEditItemModal(dayIndex, itemIndex) {
      this.currentDayIndex = dayIndex;
      this.currentItemIndex = itemIndex;
      this.isEditMode = true;
      const item = this.days[dayIndex].items[itemIndex];
      this.selectedItemType = item.title;
      this.tempItem = {
        title: item.title,
        alt: item.alt,
        address: item.address,
        startTime: item.startTime,
        endTime: item.endTime,
        description: item.description
      };
      this.showModal = true;
    },

    // 关闭弹窗
    closeModal() {
      this.showModal = false;
    },

    // 选择项目类型
    selectItemType(type) {
      this.selectedItemType = type;
      this.tempItem.title = type;
      // 设置默认项目名称为类型
      this.tempItem.alt = type;
    },
    
    // 获取类型描述
    getTypeDescription(type) {
      const descriptions = {
        '集散': '集散：团队集合，团队解散',
        '交通': '交通类型：实际交通以行程安排为准',
        '餐饮': '餐饮类型：含，午餐/特色餐',
        '活动': '活动解释：景点，娱乐等活动',
        '住宿': '住宿标准：酒店，餐饮，房型，配套等'
      };
      return descriptions[type] || '';
    },
    
    // 获取时间标签
    getTimeLabel(type) {
      const labels = {
        '集散': '参考时段',
        '交通': '参考时段',
        '餐饮': '用餐时间',
        '活动': '参考时段',
        '住宿': '入住时段'
      };
      return labels[type] || '时间';
    },
    
    // 获取地址占位符
    getAddressPlaceholder(type) {
      const placeholders = {
        '集散': '请填写目的地名称，或填入定位',
        '交通': '请填写目的地名称，或填入定位',
        '餐饮': '请填写目的地名称，或填入定位',
        '活动': '请填写目的地名称，或填入定位',
        '住宿': '请填写目的地名称，或填入定位'
      };
      return placeholders[type] || '请填写目的地名称，或填入定位';
    },
    
    // 获取地址名称（拆分后的第二部分，显示在上面）
    getAddressName(address) {
      if (!address) return '';
      if (address.includes('-')) {
        const parts = address.split('-');
        return parts[1] ? parts[1].trim() : '';
      }
      return '';
    },
    
    // 获取地址位置（拆分后的第一部分，显示在下面）
    getAddressLocation(address) {
      if (!address) return '';
      if (address.includes('-')) {
        const parts = address.split('-');
        return parts[0].trim();
      }
      return address; // 如果没有"-"，返回原地址
    },
    
    // 获取描述文本框占位符
    getDescriptionPlaceholder(type) {
      const placeholders = {
        '集散': '请输入服务说明，如集合地点详细描述，联系人信息等',
        '交通': '请输入交通详情，交通方式，行驶时长等',
        '餐饮': '请输入餐饮特色描述',
        '活动': '请输入活动描述',
        '住宿': '请输入住宿服务内容，以及特殊要求等'
      };
      return placeholders[type] || '请输入详细说明';
    },

    // 确认弹窗操作
    confirmModalAction() {
      try {
        // 表单验证
        if (!this.selectedItemType) {
          this.$u.toast('请选择项目类型');
          return;
        }

        if (!this.tempItem.alt) {
          this.$u.toast('请输入项目名称');
          return;
        }

        if (!this.tempItem.startTime) {
          this.$u.toast('请选择开始时间');
          return;
        }

        if (!this.tempItem.endTime) {
          this.$u.toast('请选择结束时间');
          return;
        }

        if (this.isEditMode) {
          // 编辑模式
          this.$set(this.days[this.currentDayIndex].items, this.currentItemIndex, { ...this.tempItem });
          this.$u.toast('修改成功');
        } else {
          // 添加模式
          if (!this.days[this.currentDayIndex].items) {
            this.days[this.currentDayIndex].items = [];
          }
          this.days[this.currentDayIndex].items.push({ ...this.tempItem });
          this.$u.toast('添加成功');
        }

        // 关闭弹窗
        this.closeModal();
      } catch (error) {
        console.error('操作失败:', error);
        this.$u.toast('操作失败，请重试');
      }
    },

    // 确认删除项目
    confirmDeleteItem(dayIndex, itemIndex) {
      try {
        uni.showModal({
          title: '确认删除',
          content: '确定要删除此项目吗？',
          confirmText: '确定',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.deleteItem(dayIndex, itemIndex);
            }
          }
        });
      } catch (error) {
        console.error('确认删除项目失败:', error);
      }
    },

    // 删除项目
    deleteItem(dayIndex, itemIndex) {
      try {
        if (this.days[dayIndex] && this.days[dayIndex].items) {
          this.days[dayIndex].items.splice(itemIndex, 1);
          this.$u.toast('删除成功');
        }
      } catch (error) {
        console.error('删除项目失败:', error);
        this.$u.toast('删除失败，请重试');
      }
    },

    // 确认删除天数
    confirmDeleteDay(dayIndex) {
      try {
        // 检查是否有项目
        const hasItems = this.days[dayIndex] && this.days[dayIndex].items && this.days[dayIndex].items.length > 0;

        // 根据是否有项目显示不同的确认信息
        const confirmContent = hasItems
          ? '该天包含行程项目，确定要删除吗？删除后不可恢复。'
          : '确定要删除这一天吗？';

        uni.showModal({
          title: '确认删除',
          content: confirmContent,
          confirmText: '确定',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.deleteDay(dayIndex);
            }
          }
        });
      } catch (error) {
        console.error('确认删除天数失败:', error);
      }
    },

    // 删除天数
    deleteDay(dayIndex) {
      try {
        if (this.days.length <= 1) {
          this.$u.toast('至少保留一天行程');
          return;
        }

        // 删除指定天数
        this.days.splice(dayIndex, 1);

        // 重新计算剩余天数的day属性
        this.days.forEach((day, index) => {
          day.day = index + 1;
        });

        this.$u.toast('删除成功');
      } catch (error) {
        console.error('删除天数失败:', error);
        this.$u.toast('删除失败，请重试');
      }
    },

    // 添加天数 - 直接跳转到itinerarySon页面（在最后添加）
    addDay() {
      // 直接跳转到itinerarySon页面，传递新添加的天数索引
      uni.navigateTo({
        url: `/public/create/itinerarySon?dayIndex=${this.days.length}&isNewDay=true&addPosition=after`
      });
    },

    // 添加上一日行程 - 直接跳转到itinerarySon页面（在前面添加）
    addDayBefore() {
      // 直接跳转到itinerarySon页面，传递新添加的天数索引（0，因为是插入到开头）
      uni.navigateTo({
        url: `/public/create/itinerarySon?dayIndex=0&isNewDay=true&addPosition=before`
      });
    },


    // 生成store数据
    generateStoreData() {
      try {
        // 移除不需要的属性
        return this.days.map(day => ({
          items: day.items || [],
          day: day.day || 0,
          main: day.main || ''
        }));
      } catch (error) {
        console.error('生成store数据失败:', error);
        return [];
      }
    },

    // 保存方法
    onSave() {
      try {
        // 生成store数据
        const storeData = this.generateStoreData();

        // 验证表单
        if (!this.validateForm()) {
          return;
        }

        // 更新store
        if (this.productStore && typeof this.productStore.updateSubPageData === 'function') {
          this.productStore.updateSubPageData('specificItinerary', storeData);
        }

        // 返回上一页
        uni.navigateBack();
      } catch (error) {
        console.error('保存行程失败:', error);
        this.$u.toast('保存失败，请重试');
      }
    },

    // 验证表单
    validateForm() {
      try {
        // 检查是否有天数
        if (this.days.length === 0) {
          this.$u.toast('请至少添加一天行程');
          return false;
        }

        // 检查每天是否有内容
        let hasContent = false;
        for (let i = 0; i < this.days.length; i++) {
          if (this.days[i] && this.days[i].items && this.days[i].items.length > 0) {
            hasContent = true;
            break;
          }
        }

        if (!hasContent) {
          this.$u.toast('请至少添加一个行程项目');
          return false;
        }

        return true;
      } catch (error) {
        console.error('验证表单失败:', error);
        return false;
      }
    },

    // 返回方法
    goBack() {
      try {
        // 询问用户是否保存
        let hasUnsavedChanges = false;
        for (let i = 0; i < this.days.length; i++) {
          if (this.days[i] && this.days[i].items && this.days[i].items.length > 0) {
            hasUnsavedChanges = true;
            break;
          }
        }

        if (hasUnsavedChanges) {
          this.$u.modal.confirm({
            title: '提示',
            content: '有未保存的内容，是否保存？',
            confirmText: '保存',
            cancelText: '不保存',
            success: (res) => {
              if (res.confirm) {
                this.onSave();
              } else if (res.cancel) {
                uni.navigateBack();
              }
            }
          });
        } else {
          uni.navigateBack();
        }
      } catch (error) {
        console.error('返回操作失败:', error);
        uni.navigateBack();
      }
    },

    // 打开时间选择器
    showTimePicker(type) {
      try {
        // 设置时间选择器的类型
        this.timePickerType = type;

        // 获取当前时间值
        const currentTime = type === 'start' ? this.tempItem.startTime : this.tempItem.endTime;

        // 如果已有时间值且是HH:MM格式，直接使用
        if (currentTime && /^\d{2}:\d{2}$/.test(currentTime)) {
          this.timePickerValue = currentTime;
        } else {
          // 否则使用当前时间的时分
          const date = new Date();
          const formattedTime = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
          this.timePickerValue = formattedTime;
        }

        // 显示时间选择器
        this.isShowTimePicker = true;
      } catch (error) {
        console.error('显示时间选择器失败:', error);
        uni.showToast({
          title: '时间选择失败',
          icon: 'none'
        });
      }
    },

    // 确认时间选择
    confirmTimePicker() {
      try {
        // 直接使用时间选择器的值（HH:MM格式）
        const timeValue = this.timePickerValue;

        // 更新对应的时间字段
        if (this.timePickerType === 'start') {
          this.tempItem.startTime = timeValue;
        } else {
          this.tempItem.endTime = timeValue;
        }

        // 关闭时间选择器
        this.isShowTimePicker = false;
      } catch (error) {
        console.error('确认时间选择失败:', error);
        uni.showToast({
          title: '时间设置失败',
          icon: 'none'
        });
      }
    },

    // 取消时间选择
    cancelTimePicker() {
      this.isShowTimePicker = false;
    },

    // 选择地址
    selectAddress() {
      try {
        // 使用uni.chooseLocation API选择地址
        uni.chooseLocation({
          success: (res) => {
            // res.address 是详细地址，res.name 是地址名称
            const selectedAddress = `${res.address}${res.name ? ' ' + res.name : ''}`;
            this.tempItem.address = selectedAddress;
          },
          fail: (error) => {
            // 如果用户取消选择，不显示错误提示
            if (error.errMsg !== 'chooseLocation:fail cancel') {
              console.error('选择地址失败:', error);
              uni.showToast({
                title: '地址选择失败',
                icon: 'none'
              });
            }
          }
        });
      } catch (error) {
        console.error('选择地址失败:', error);
        uni.showToast({
          title: '地址选择失败',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
	
.itinerary-editor {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

.content-wrapper {
  padding: 30rpx;
}

.day-title {
  position: absolute;
  left: 20rpx;
  top:16rpx;
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 30rpx;
  color:#666;
}

.days-container {
  display: flex;
  flex-direction: column;
  
}

.day-card {
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 20rpx;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20rpx 0rpx 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.day-tag-container {
  display: flex;
  flex: 1;
  align-items: flex-start;
  
  .day-item-title{
	  margin-top: 10rpx;
	  font-weight: 700;
	  font-style: normal;
	  font-size: 30rpx;
	  color: #303030;
	  text-align: left;
  }
}

.day-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
  background-color: #3FBDA3;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  height: 64rpx;
  line-height: 64rpx;
  padding: 0rpx 20rpx;
  border-top-right-radius: 5000rpx;
  border-bottom-right-radius: 5000rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.day-content-text {
  flex: 1;
  font-size: 28rpx;
  line-height: 1.5;
  color: #333;
  white-space: pre-line;
}

.expand-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
}

.arrow-icon {
  width: 48rpx;
  height: 48rpx;
  transition: transform 0.3s ease;
  transform: rotate(0deg);
}

.arrow-expanded {
  transform: rotate(180deg);
}

.day-details {
  padding: 20rpx;
}

.itinerary-detail-item {
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.item-time-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx;
  margin-bottom: 16rpx;
  .item-time-container-left{
	  display: flex;
	  align-items: center;
	  justify-content: flex-start;
  }
}

.item-time {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;
}

.item-type {
  font-size: 28rpx;
  color: #666;
}

.item-separator {
  margin: 0 10rpx;
  color: #999;
}

.item-name {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.item-details {
  margin-left: 20rpx;
  margin-bottom: 20rpx;
}

.item-detail-row {
  display: flex;
  margin-bottom: 10rpx;
  font-size: 24rpx;
  line-height: 1.5;
}

.detail-label {
  color: #999;
  margin-right: 20rpx;
  min-width: 70rpx;
  display:flex;
  align-items: center;
  justify-content: flex-end;
  .detail-label-icon{
	  width:28rpx;
	  height:28rpx;
  }
}

.detail-value {
  color: #666;
  flex: 1;
}

.address-display {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.address-name {
  font-size: 26rpx;
  color: #333;
  font-weight: 700;
  line-height: 1.4;
}

.address-location {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  margin-left: 0; /* 确保与name左对齐 */
}

/* 地址标签与name对齐 */
.item-detail-row .detail-label {
  align-items: flex-start;
  padding-top: 2rpx; /* 微调对齐 */
}

/* 地址显示区域自动适应高度 */
.item-detail-row .detail-value {
  min-height: auto;
  height: auto;
  word-wrap: break-word;
  word-break: break-all;
  white-space: normal;
}

.item-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn {
  flex-shrink: 0;
  padding: 20rpx 12rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.edit-btn {
  color: #1890ff;
  border: 1rpx solid #91d5ff;
}

.delete-btn {
  background-color: #fff1f0;
  color: #ff4d4f;
  border: 1rpx solid #ffa39e;
}

.add-item-section {
  margin-top: 20rpx;
}

.add-item-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  cursor: pointer;
}

.btn-plus {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  background-color: #00c389;
  border-radius: 50%;
  font-size: 28rpx;
  color: #fff;
  margin-right: 16rpx;
  flex-shrink: 0;
}

.btn-text {
  font-size: 28rpx;
  color: #666;
}

.add-day-section {
  
}

.add-day-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background-color: #ffffff;
  border-radius: 8rpx;
  cursor: pointer;
}

/* 模态框样式 */
.modal-content {
  padding: 30rpx;
}

/* 标题输入弹窗样式 */
.title-modal-content {
  padding: 30rpx;
  width:100%;
}

.title-textarea {
  width: 100%;
  min-height: 80rpx;
  max-height: 200rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  box-sizing: border-box;
  margin-top: 20rpx;
  resize: none;
  overflow-y: auto;
}

.modal-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
  gap: 20rpx;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1rpx solid #e0e0e0;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.day-selector {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.itinerary-type-card {
  padding: 20rpx;
  border-radius: 8rpx;
  border: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.selected {
  border-color: #00c389;
  background-color: #f0fff9;
}

.type-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.type-title {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.type-name {
  font-size: 28rpx;
  color: #666;
  margin-right: auto;
}

.active {
  color: #00c389;
  font-weight: bold;
}

.type-description {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.time-range-container, .address-container {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.time-label, .address-label {
  font-size: 26rpx;
  color: #666;
  width: 140rpx;
}

.time-pickers {
  display: flex;
  align-items: center;
  flex: 1;
}

.time-picker-btn {
  background-color: #f5f5f5;
  border-radius: 4rpx;
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #333;
}

.time-separator {
  margin: 0 10rpx;
  color: #999;
}

.address-select-btn {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 4rpx;
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #333;
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.description-container {
  margin-bottom: 20rpx;
}

.form-textarea {
  width: 100%;
  height: 160rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 26rpx;
  color: #333;
}

.service-detail-container {
  display: flex;
  justify-content: flex-end;
}

.service-detail-btn {
  font-size: 24rpx;
  color: #999;
  display: flex;
  align-items: center;
}

.modal-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.cancel-btn {
  margin-right: 20rpx;
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #00c389;
  color: #fff;
}

/* 时间选择器容器样式 */
.time-picker-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99999;
}
</style>